package Connections;

import Gear.Factory;

import java.io.File;
import java.net.Socket;
import java.nio.file.FileSystems;

/**
 * Thread that deal with a new connection on peer server.
 *
 * @author Rodrigo Martins Racanici
 */
public class PeerHandler extends ConnectionHandler {

    /**
     * Handler constructor.
     *
     * @param client
     */
    public PeerHandler(Socket client) {
        super(client);
    }

    /**
     * Deal with a new connection.
     */
    @Override
    public void run() {

        String[] command = Factory.getInstance().getPeerServer().receiveCommand(client).trim().split(";");

        for (String c : command) {
            String[] args = c.trim().split("\"{1,2}");
            File f;
            if (args[0].trim().equals("ResquestFile")) {
                if ((f = FileSystems.getDefault().getPath(Factory.getInstance().getSettings().getGearPath().toString(), args[1].trim()).toFile()).exists()) {
                    Factory.getInstance().getLocalFileMutex().acquire(args[1]);

                    Factory.getInstance().getPeerServer().sendCommand(client, "Ok");
                    Factory.getInstance().getPeerServer().sendFile(client, f);

                    Factory.getInstance().getLocalFileMutex().release(args[1]);
                    return;
                }
            } else if (args[0].trim().equals("SyncFile")) {
                new DownloaderClient(args[2]).dowload(args[1]);
                return;
            } else if (args[0].trim().equals("Close")) {
                Factory.getInstance().getPeerServer().closeClient(client);
                return;
            }

            Factory.getInstance().getPeerServer().sendCommand(client, "Error");
            Factory.getInstance().getPeerServer().closeClient(client);
        }
    }
}

